<template>
	<view class="content">
		<!-- 顶部标题区域 -->
		<view class="header-section">
			<view class="app-logo">🪶🪶</view>
			<view class="app-name">两只羽毛</view>
			<view class="app-slogan">真诚相遇 · 携手一生</view>
		</view>
		
		<!-- 登录框 -->
		<view class="login-box">
			<!-- 切换标签 -->
			<view class="login-tabs">
				<view class="tab-item" :class="{active: loginMode === 'phone'}" @click="loginMode = 'phone'">
					<text class="tab-icon">📱</text>
					<text>验证码登录</text>
				</view>
				<view class="tab-item" :class="{active: loginMode === 'password'}" @click="loginMode = 'password'">
					<text class="tab-icon">🔐</text>
					<text>密码登录</text>
				</view>
			</view>
			
			<!-- 手机号验证码登录 -->
			<view v-if="loginMode === 'phone'">
				<view class="login-title">
					<text class="title-icon">💌</text>
					<text>快速登录</text>
				</view>
				<view class="form-group">
					<input class="input" type="number" maxlength="11" v-model="phoneForm.phone" placeholder="请输入手机号" />
				</view>
				<view class="form-group code-group">
					<input class="input code-input" type="number" maxlength="6" v-model="phoneForm.code" placeholder="请输入验证码" />
					<view class="code-btn" :class="{disabled: countdown > 0}" @click="sendCode">
						{{ countdown > 0 ? `${countdown}秒` : '发送验证码' }}
					</view>
				</view>
				<button class="login-btn" @click="handlePhoneLogin">登录</button>
				
				<!-- 微信一键登录 -->
				<view class="divider">
					<view class="line"></view>
					<text class="text">其他方式登录</text>
					<view class="line"></view>
				</view>
				
			<button class="wechat-login-btn" @click="login_zheshow">
				<text class="wechat-icon">💬</text>
				<text>微信一键登录</text>
			</button>
			</view>
			
			<!-- 账号密码登录 -->
			<view v-if="loginMode === 'password'">
				<view class="login-title">
					<text class="title-icon">💝</text>
					<text>账号登录</text>
				</view>
				<view class="form-group">
					<input class="input" v-model="passwordForm.username" placeholder="请输入账号或手机号" />
				</view>
				<view class="form-group password-group">
					<input class="input" :type="showPassword ? 'text' : 'password'" v-model="passwordForm.password" placeholder="请输入密码" />
					<view class="eye-icon" @click="showPassword = !showPassword">
						{{ showPassword ? '👁️' : '👁️‍🗨️' }}
					</view>
				</view>
				<view class="remember-row">
					<view class="remember-check" @click="rememberMe = !rememberMe">
						<image :src="rememberMe ? '/static/4checked.png' : '/static/4unchecked.png'" class="checkbox-icon"></image>
						<text>记住密码</text>
					</view>
				</view>
				<button class="login-btn" @click="handlePasswordLogin">登录</button>
				
				<!-- 微信一键登录 -->
				<view class="divider">
					<view class="line"></view>
					<text class="text">其他方式登录</text>
					<view class="line"></view>
				</view>
				
			<button class="wechat-login-btn" @click="login_zheshow">
				<text class="wechat-icon">💬</text>
				<text>微信一键登录</text>
			</button>
			</view>
		</view>
		
		<!-- 底部提示 -->
		<view class="footer-tip">
			<text class="tip-icon">💗</text>
			<text class="tip-text">遇见对的人，不再孤单</text>
		</view>
		
		<btnlogin :zheshow='zheshow' />
	</view>
</template>

<script>
    import btnlogin from '@/components/butlogin';
    import api from '@/utils/api.js'
    import userAuth from '@/utils/userAuth.js'
    export default {
        components:{
            btnlogin
        },
        data() {
            return {
                zheshow: false, // 控制弹窗显示隐藏
                loginMode: 'phone', // 登录模式：phone-验证码登录，password-密码登录
                redirectUrl: '', // 登录成功后跳转地址（可选）
                
                // 手机号验证码登录
                phoneForm: {
                    phone: '',
                    code: ''
                },
                countdown: 0, // 倒计时
                countdownTimer: null,
                
                // 账号密码登录
                passwordForm: {
                    username: '',
                    password: ''
                },
                showPassword: false, // 是否显示密码
                rememberMe: false // 记住密码
            }
        },
        
        onLoad(options) {
            // 加载记住的密码
            this.loadRememberedPassword();
            // 处理跳转参数
            this.redirectUrl = options && options.redirect ? decodeURIComponent(options.redirect) : ''
        },
		
		onUnload() {
			// 清除倒计时
			if (this.countdownTimer) {
				clearInterval(this.countdownTimer);
			}
		},
		
		methods: {
			login_zheshow(){
				this.zheshow = !this.zheshow
			},
		loset(Logon_Credentials){
			console.log(Logon_Credentials,'登录信息')
			// 获取微信登录code
			uni.login({
				provider: 'weixin',
				success: async (loginRes) => {
					uni.showLoading({ title: '登录中...' })
					try {
						// 1. 微信授权登录
						const wechatLoginResult = await api.auth.wechatLogin(loginRes.code)
						const token = wechatLoginResult?.token || wechatLoginResult?.data?.token
						const user = wechatLoginResult?.user || wechatLoginResult?.data?.user
						
						if (!token || !user) {
							throw new Error('微信登录返回数据异常')
						}
						
						console.log('✅ 微信登录成功，用户ID:', user.userId)
						
						// 2. 获取手机号
						const phoneCode = (Logon_Credentials && Logon_Credentials.code && String(Logon_Credentials.code).trim()) ? String(Logon_Credentials.code).trim() : 'mock_dev_code'
						console.log('📱 使用phoneCode:', phoneCode)
						
						try {
							const phoneResult = await api.auth.wechatPhone(phoneCode)
							const phone = phoneResult?.phone || phoneResult?.data?.phone
							
							if (phone) {
								console.log('✅ 成功获取手机号')
								user.phone = phone
							} else {
								console.warn('⚠️ 手机号为空，使用默认值（开发环境）')
								// 开发环境：如果后端返回了mock手机号，也可能在user对象中
								user.phone = user.phone || '13800138000'
							}
						} catch (phoneError) {
							console.error('❌ 获取手机号接口失败:', phoneError)
							// 开发环境容错：继续登录，使用默认手机号
							user.phone = user.phone || '13800138000'
							console.warn('⚠️ 使用默认手机号继续登录（开发环境）')
						}
						
						// 3. 更新用户信息（昵称和头像）
						user.nickname = Logon_Credentials.nickname || user.nickname
						user.avatar = Logon_Credentials.active || user.avatar
						
						console.log('💾 保存用户信息:', { userId: user.userId, phone: user.phone, nickname: user.nickname })
						
						// 4. 保存登录信息
						userAuth.saveLoginInfo(token, user)
						
						uni.hideLoading()
						uni.showToast({ title: '登录成功', icon: 'success' })
						
						// 5. 跳转首页
						setTimeout(() => {
							const target = this.redirectUrl || '/pages/index/index'
							uni.reLaunch({ url: target })
						}, 500)
					} catch (error) {
						console.error('❌ 微信登录失败:', error)
						uni.hideLoading()
						uni.showToast({ 
							title: error?.message || '登录失败，请重试', 
							icon: 'none',
							duration: 2000
						})
					}
				},
				fail: (err) => {
					console.error('获取微信code失败:', err)
					uni.showToast({ title: '微信登录失败', icon: 'none' })
				}
			})
		},
			
			// 发送验证码
			async sendCode() {
				if (this.countdown > 0) return;
				
				// 验证手机号
				if (!this.phoneForm.phone) {
					uni.showToast({ title: '请输入手机号', icon: 'none' });
					return;
				}
				
				if (!/^1[3-9]\d{9}$/.test(this.phoneForm.phone)) {
					uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
					return;
				}
				
				try {
					uni.showLoading({ title: '发送中...' })
					await api.auth.sendCode(this.phoneForm.phone)
					uni.showToast({ title: '验证码已发送', icon: 'success' });
					// 开始倒计时
					this.countdown = 60;
					this.countdownTimer = setInterval(() => {
						this.countdown--;
						if (this.countdown <= 0) {
							clearInterval(this.countdownTimer);
						}
					}, 1000);
				} catch (err) {
					console.error('发送验证码失败:', err)
					uni.showToast({ title: err?.message || '发送失败', icon: 'none' })
				} finally {
					uni.hideLoading()
				}
			},
			
			// 手机号验证码登录
			async handlePhoneLogin() {
				if (!this.phoneForm.phone) {
					uni.showToast({ title: '请输入手机号', icon: 'none' });
					return;
				}
				
				if (!this.phoneForm.code) {
					uni.showToast({ title: '请输入验证码', icon: 'none' });
					return;
				}
				
				uni.showLoading({ title: '登录中...' });
				try {
					const result = await api.auth.smsLogin(this.phoneForm.phone, this.phoneForm.code)
					const token = result?.token || result?.data?.token
					const user = result?.user || result?.data?.user
					if (!token || !user) {
						throw new Error('登录返回数据异常')
					}
					// 保存登录信息
					userAuth.saveLoginInfo(token, user)
					uni.showToast({ title: '登录成功', icon: 'success' })
					// 跳转首页
					const target = this.redirectUrl || '/pages/index/index'
					uni.reLaunch({ url: target })
					// 清空表单
					this.phoneForm = { phone: '', code: '' }
				} catch (error) {
					console.error('验证码登录失败:', error)
					uni.showToast({ title: error?.message || '登录失败', icon: 'none' })
				} finally {
					uni.hideLoading()
				}
			},
			
            // 账号密码登录
            async handlePasswordLogin() {
                if (!this.passwordForm.username) {
                    uni.showToast({ title: '请输入账号', icon: 'none' });
                    return;
                }
                
                if (!this.passwordForm.password) {
                    uni.showToast({ title: '请输入密码', icon: 'none' });
                    return;
                }
                
                // 调用后端API进行登录
                uni.showLoading({ title: '登录中...' });
                try {
                    const result = await api.auth.loginByPassword(this.passwordForm.username, this.passwordForm.password)
                    // 兼容不同返回结构
                    const token = result?.token || result?.data?.token
                    const user = result?.user || result?.data?.user
                    if (!token || !user) {
                        throw new Error('登录返回数据异常')
                    }

                    // 使用工具类保存登录信息 - 确保userId正确处理
                    console.log('登录成功，用户信息:', user)
                    console.log('用户ID类型和值:', typeof user.userId, user.userId)
                    
                    // 确保userId是数字类型
                    if (user.userId) {
                        user.userId = parseInt(user.userId)
                        console.log('处理后的用户ID:', user.userId)
                    }
                    
                    userAuth.saveLoginInfo(token, user)

                    // 是否记住密码
                    if (this.rememberMe) {
                        uni.setStorageSync('rememberedAccount', {
                            username: this.passwordForm.username,
                            password: this.passwordForm.password
                        })
                    } else {
                        uni.removeStorageSync('rememberedAccount')
                    }

                    uni.showToast({ title: '登录成功', icon: 'success' })

                    // 跳转页面（统一使用 reLaunch 进入首页或指定页面）
                    const target = this.redirectUrl || '/pages/index/index'
                    uni.reLaunch({ url: target })

                    // 清空表单
                    this.passwordForm = { username: '', password: '' }
                } catch (error) {
                    console.error('登录失败:', error)
                    uni.showToast({ title: error?.message || '登录失败', icon: 'none' })
                } finally {
                    uni.hideLoading()
                }
            },
			
			// 加载记住的密码
			loadRememberedPassword() {
				const remembered = uni.getStorageSync('rememberedAccount');
				if (remembered) {
					this.passwordForm.username = remembered.username;
					this.passwordForm.password = remembered.password;
					this.rememberMe = true;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
.content {
	padding: 40rpx;
	background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 50%, #ffe9f0 100%);
	min-height: 100vh;
	position: relative;
	
	// 添加装饰性元素
	&::before {
		content: '❤️';
		position: absolute;
		top: 100rpx;
		right: 60rpx;
		font-size: 60rpx;
		opacity: 0.2;
		animation: heartbeat 2s infinite;
	}
	
	&::after {
		content: '💕';
		position: absolute;
		bottom: 200rpx;
		left: 40rpx;
		font-size: 50rpx;
		opacity: 0.2;
		animation: heartbeat 2s infinite 0.5s;
	}
}

@keyframes heartbeat {
	0%, 100% {
		transform: scale(1);
	}
	50% {
		transform: scale(1.1);
	}
}

.header-section {
	text-align: center;
	margin-bottom: 60rpx;
	
	.app-logo {
		font-size: 120rpx;
		margin-bottom: 20rpx;
		animation: heartbeat 2s infinite;
	}
	
	.app-name {
		font-size: 48rpx;
		font-weight: bold;
		background: linear-gradient(135deg, #ff6b9d 0%, #ff8fab 100%);
		-webkit-background-clip: text;
		-webkit-text-fill-color: transparent;
		margin-bottom: 15rpx;
	}
	
	.app-slogan {
		font-size: 26rpx;
		color: #ff6b9d;
		opacity: 0.8;
	}
}

.login-box {
	background: #FFFFFF;
	border-radius: 30rpx;
	padding: 50rpx 40rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 8rpx 24rpx rgba(255, 107, 157, 0.15);
	border: 2rpx solid rgba(255, 107, 157, 0.1);
	
	.login-tabs {
		display: flex;
		background: linear-gradient(135deg, #fff0f6 0%, #ffe9f0 100%);
		border-radius: 50rpx;
		padding: 6rpx;
		margin-bottom: 40rpx;
		
		.tab-item {
			flex: 1;
			height: 70rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 26rpx;
			color: #ff6b9d;
			border-radius: 50rpx;
			transition: all 0.3s;
			
			.tab-icon {
				font-size: 32rpx;
				margin-right: 8rpx;
			}
			
			&.active {
				background: linear-gradient(135deg, #ff6b9d 0%, #ff8fab 100%);
				color: #FFFFFF;
				font-weight: bold;
				box-shadow: 0 4rpx 12rpx rgba(255, 107, 157, 0.3);
			}
		}
	}
	
	.login-title {
		font-size: 34rpx;
		font-weight: bold;
		color: #ff6b9d;
		margin-bottom: 40rpx;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
		
		.title-icon {
			font-size: 40rpx;
			margin-right: 10rpx;
		}
	}
	
	.form-group {
		margin-bottom: 25rpx;
		position: relative;
		
		.input {
			width: 100%;
			height: 90rpx;
			background: #fff5f9;
			border-radius: 50rpx;
			padding: 0 30rpx;
			font-size: 28rpx;
			border: 2rpx solid #ffe0ed;
			box-sizing: border-box;
			transition: all 0.3s;
			
			&:focus {
				background: #FFFFFF;
				border-color: #ff8fab;
			}
		}
		
		&.code-group {
			display: flex;
			align-items: center;
			
			.code-input {
				flex: 1;
				margin-right: 20rpx;
			}
			
			.code-btn {
				width: 180rpx;
				height: 80rpx;
				background: linear-gradient(135deg, #ff6b9d 0%, #ff8fab 100%);
				color: #FFFFFF;
				border-radius: 50rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				box-shadow: 0 4rpx 12rpx rgba(255, 107, 157, 0.3);
				
				&.disabled {
					background: #e8e8e8;
					color: #999999;
					box-shadow: none;
				}
			}
		}
		
		&.password-group {
			display: flex;
			align-items: center;
			
			.input {
				flex: 1;
				padding-right: 80rpx;
			}
			
			.eye-icon {
				position: absolute;
				right: 20rpx;
				font-size: 40rpx;
				padding: 10rpx;
			}
		}
	}
	
	.remember-row {
		margin-bottom: 25rpx;
		
		.remember-check {
			display: flex;
			align-items: center;
			font-size: 26rpx;
			color: #666666;
			
			.checkbox-icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 10rpx;
			}
		}
	}
	
	.login-btn {
		width: 100%;
		height: 90rpx;
		background: linear-gradient(135deg, #ff6b9d 0%, #ff8fab 100%);
		color: #FFFFFF;
		border-radius: 50rpx;
		font-size: 32rpx;
		font-weight: bold;
		border: none;
		box-shadow: 0 8rpx 20rpx rgba(255, 107, 157, 0.4);
		margin-bottom: 30rpx;
		
		&:active {
			opacity: 0.9;
			transform: translateY(2rpx);
		}
	}
	
	.divider {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		
		.line {
			flex: 1;
			height: 1rpx;
			background: linear-gradient(to right, transparent, #ffcce0, transparent);
		}
		
		.text {
			margin: 0 20rpx;
			font-size: 24rpx;
			color: #ff6b9d;
		}
	}
	
	.wechat-login-btn {
		width: 100%;
		height: 90rpx;
		background: linear-gradient(135deg, #ff6b9d 0%, #ff8fab 100%);
		color: #FFFFFF;
		border-radius: 50rpx;
		font-size: 30rpx;
		font-weight: bold;
		display: flex;
		align-items: center;
		justify-content: center;
		border: none;
		box-shadow: 0 8rpx 20rpx rgba(255, 107, 157, 0.4);
		
		.wechat-icon {
			font-size: 40rpx;
			margin-right: 10rpx;
		}
		
		&:active {
			opacity: 0.9;
			transform: translateY(2rpx);
		}
	}
}

.footer-tip {
	text-align: center;
	margin-top: 60rpx;
	padding: 30rpx;
	
	.tip-icon {
		font-size: 50rpx;
		display: block;
		margin-bottom: 15rpx;
		animation: heartbeat 2s infinite;
	}
	
	.tip-text {
		font-size: 26rpx;
		color: #ff6b9d;
		font-weight: 500;
		letter-spacing: 2rpx;
	}
}

button {
	&::after {
		border: none;
	}
}
</style>
